package compilers.node;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

import compilers.Node;
import compilers.stmt.Var;
import compilers.table.MemScope;

public class Program extends Node {
	Vector<Node> fChildren = new Vector<Node>();
	Vector<Var> fVars = new Vector<Var>();
	
	public void print(int tab) {
		System.out.println("[ Small C Program ]");
		
		Enumeration<Var> enumeration = fVars.elements();
		while(enumeration.hasMoreElements()){
			((Node) enumeration.nextElement()).print(tab+1);
		}
		
		Enumeration<Node> enumeration2 = fChildren.elements();
		while(enumeration2.hasMoreElements()){
			((Node) enumeration2.nextElement()).print(tab+1);
		}  
	}

	public void addChild(Node fNode) {		
		if (fNode instanceof VarList) {
			VarList v = (VarList)fNode;
			for (int i = 0; i < v.fVars.size(); i++) {
				v.fVars.get(i).setInit();
				fVars.add(v.fVars.get(i));
			}
		} else {
			fChildren.add(fNode);
		}
	}

	public void generate(BufferedWriter writer, MemScope scope) throws IOException {
		MemScope myScope = new MemScope(scope);
		//writer.write("ujp program\n");
		//writer.write("program:\n");
		writer.write("mst 0\n");
		
		Enumeration<Var> enumeration = fVars.elements();
		while(enumeration.hasMoreElements()){
			((Node) enumeration.nextElement()).generate(writer, myScope);
		}
		
		writer.write("cup 0 func_main\n");
		writer.write("hlt\n");
		
		Enumeration<Node> enumeration2 = fChildren.elements();
		while(enumeration2.hasMoreElements()){
			((Node) enumeration2.nextElement()).generate(writer, myScope);
		}  
	}
}
